 <template>
  <div class="order-detail-container">
    <!-- 顶部标题和状态 -->
    <div class="header">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/order' }">交易管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/order' }">订单列表</el-breadcrumb-item>
        <el-breadcrumb-item>订单详情</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="status-info">
        <el-tag :type="getStatusTagType(order.status)" size="large">{{ order.status }}</el-tag>
      </div>
    </div>

    <!-- 订单状态详情 -->
    <div class="status-detail">
      <div v-if="order.status === '待支付'" class="status-message warning">
        <p>商品已拍下，等待买家付款。</p>
        <p v-if="remainingTime">如买家未在{{ remainingTime }}内付款，订单将按自动关闭。</p>
      </div>
      <div v-else-if="order.status === '已支付'" class="status-message success">
        <p>交易成功，买家已付款，交易已完成。</p>
      </div>
      <div v-else-if="order.status === '已关闭'" class="status-message danger">
        <p>交易关闭。支付超时，订单自动关闭。</p>
      </div>
      <div v-else-if="order.status === '支付超时'" class="status-message danger">
        <p>支付超时，自动取消支付，订单关闭。</p>
      </div>
      <div v-else-if="order.status === '退款中'" class="status-message info">
        <p>申请退款，买家申请退款，等待商家同意。</p>
      </div>
      <div v-else-if="order.status === '已退款'" class="status-message success">
        <p>退款完成，订单关闭。</p>
      </div>

      <!-- 售后详情模块 -->
      <div class="section" v-if="order.status === '已退款'">
        <div class="section-title">售后详情</div>
        <div class="refund-detail">
          <div class="detail-row">
            <span>售后状态：</span>
            <span>已退款</span>
          </div>
          <div class="detail-row">
            <span>退款金额：</span>
            <span>¥{{ order.refund_amount || '3999' }}</span>
          </div>
          <div class="detail-row">
            <span>退款渠道：</span>
            <span>{{ order.refund_channel || '原支付渠道退回' }}</span>
          </div>
          <div class="detail-row">
            <span>退款原因：</span>
            <span>{{ order.refund_reason || '不想要了' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 备注信息 -->
    <div class="section">
      <div class="section-title">订单备注</div>
      <div class="note-container">
        <div class="note-content">
          <el-input
            v-if="isEditingNote"
            v-model="tempNote"
            type="textarea"
            :rows="3"
            placeholder="请输入备注内容"
            resize="none"
          ></el-input>
          <div v-else class="note-text">
            {{ order.notes || '暂无备注' }}
          </div>
        </div>
        <div class="note-actions">
          <el-button 
            v-if="!isEditingNote"
            type="primary" 
            plain 
            size="small"
            @click="isEditingNote = true"
          >
            编辑备注
          </el-button>
          <template v-else>
            <el-button 
              type="success" 
              plain 
              size="small"
              @click="saveNote"
            >
              保存
            </el-button>
            <el-button 
              type="info" 
              plain 
              size="small"
              @click="isEditingNote = false"
            >
              取消
            </el-button>
          </template>
        </div>
      </div>
    </div>

    <!-- 用户信息 -->
    <div class="section">
      <div class="section-title">用户信息</div>
      <div class="user-info">
        <div class="user-header">
          <span class="user-name">{{ order.user_name || '未知用户' }}</span>
        </div>
      </div>
    </div>

    <!-- 订单信息 -->
    <div class="section">
      <div class="section-title">订单信息</div>
      <div class="order-info">
        <div class="detail-row">
          <span>订单编号: {{ order.order_id }}</span>
          <el-button type="text" @click="copyOrderId">复制</el-button>
        </div>
        <div class="detail-row">
          <span>下单时间: {{ formatDateTime(order.order_time) }}</span>
        </div>
        <div class="detail-row">
          <span>订单状态: {{ getStatusText(order.status) }}</span>
        </div>
      </div>
    </div>

    <!-- 商品信息 -->
    <div class="section">
      <div class="section-title">商品信息</div>
      <el-table :data="[order]" style="width: 100%" border>
        <el-table-column prop="courseName" label="课程信息" width="300"></el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template #default="{ row }">¥{{ Number(row.price).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="pay_method" label="支付方式" width="120">
          <template #default="{ row }">{{ getPaymentMethodText(row.pay_method) }}</template>
        </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default>
                      <el-button 
                        v-if="order.status === '已支付'"
                        type="text" 
                        size="small"
                        @click="handleRefund"
                      >退款</el-button>
                      <span v-else>&nbsp;</span>
                    </template>
                  </el-table-column>
      </el-table>

      <div class="price-summary">
        <div class="summary-row">
          <span>商品总价：</span>
          <span>¥{{ Number(order.price).toFixed(2) }}</span>
        </div>
        <div class="summary-row total">
          <span>应付款：</span>
          <span>¥{{ Number(order.price).toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <div class="footer">
      <el-button @click="goBack">返回</el-button>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import AV from 'leancloud-storage'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {getorder, updateorder} from './../http/order'
import { header2 } from './../http/common'
import type { Order } from './../type/order'

const router = useRouter()  
const route = useRoute()

// 获取状态标签类型
const getStatusTagType = (status: string) => {
      const map = {
          '待支付': 'warning',
          '已支付': 'success',
          '已关闭': 'danger',
          '退款中': 'info',
          '支付超时': 'danger'
      }
  return map[status] || ''
}

// 计算剩余支付时间
const remainingTime = computed(() => {
  if (order.value.status !== '待支付' || !order.value.order_time) return null
  
  const orderTime = new Date(order.value.order_time)
  const expireTime = new Date(orderTime.getTime() + 30 * 60 * 1000) // 30分钟过期
  const now = new Date()
  
  if (now >= expireTime) return '00:00'
  
  const diff = expireTime.getTime() - now.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  const seconds = Math.floor((diff % (1000 * 60)) / 1000)
  
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})

// 订单数据
const order = ref<Order>({
  objectId: '',
  order_id: '',
  user_name: '',
  courseName: '',
  price: '0',
  status: '',
  pay_method: 'unpaid',
  notes: '',
  order_time: '',
})

onMounted(() => {
  OrderDetail()
})

async function OrderDetail() {
  try {
    const objectId = route.query.id
    if (!objectId) {
      ElMessage.error('订单ID不能为空')
      return
    }
    
    console.log('请求订单详情，objectId:', objectId)
    const response = await getorder(objectId as string)
    console.log('API响应数据:', response.data)
    console.log('用户名字段:', response.data?.results?.[0]?.user_name || response.data?.user_name)
    
    // 检查响应数据结构
    let data = response.data
    if (data.results && data.results.length > 0) {
      data = data.results[0] // LeanCloud返回的数据格式
    }
    
    if (!data || !data.objectId) {
      ElMessage.error('未找到该订单')
      return
    }
    
    order.value = {
      objectId: data.objectId || '',
      order_id: data.order_id || '',
      user_name: data.user_name || '',
      courseName: data.courseName || '',
      price: data.price ? String(data.price).trim() : '0',
      status: data.status ? String(data.status).trim() : '',
      pay_method: data.pay_method && data.pay_method.trim() ? data.pay_method.trim() : '未支付',
      notes: data.notes || '',
      order_time: data.order_time || data.createdAt || data.updatedAt || '',
    }
  } catch (e) {
    console.error('获取订单详情失败:', e)
    ElMessage.error('获取订单详情失败: ' + (e.message || '未知错误'))
  }
}


// 备注相关
const isEditingNote = ref(false)

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  if (!datetime) return ''
  return datetime.replace(/(\d{4})-(\d{2})-(\d{2})/, '$1-$2-$3')
}

// 获取支付方式文本
const getPaymentMethodText = (pay_method: string) => {
  const map = {
    '支付宝': '支付宝',
    '微信支付': '微信支付',
    '未支付': '未支付'
  }
  return map[pay_method] || pay_method || '未支付'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const map = {
    pending: '等待用户支付',
    completed: '订单完成',
    refund: '退款完成，订单关闭',
    closed: '支付超时，订单关闭'
  }
  return map[status] || status
}

// 处理退款
const handleRefund = async () => {
  try {
    const { value } = await ElMessageBox.prompt('请输入退款原因', '退款', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
    
    try {
      if (!order.value.objectId) {
        throw new Error('订单ID不能为空')
      }

      console.log('正在更新订单状态:', {
        objectId: order.value.objectId,
        status: '退款中',
        notes: value
      })
      
      // 使用项目中已有的updateorder方法
      const response = await updateorder(
        0, // 默认id
        '', // 默认planId 
        '', // 默认name
        order.value.objectId,
        {
          status: '已退款',
          notes: value,
          refund_amount: order.value.price, // 确保退款金额等于订单价格
          refund_reason: value,
          refund_channel: order.value.pay_method,
          refund_time: new Date().toISOString()
        }
      )

      console.log('退款API响应:', response)
      
      if (response.status !== 200) {
        throw new Error(`API请求失败，状态码: ${response.status}`)
      }

      // 更新本地状态
      order.value.status = '退款中'
      order.value.notes = value
    } catch (error) {
      console.error('退款API调用失败:', error)
      if (error.response) {
        console.error('API响应数据:', error.response.data)
        console.error('API响应状态:', error.response.status)
        console.error('API响应头:', error.response.headers)
      }
      throw error
    }

    // 更新本地订单数据
    order.value.status = '退款中'
    order.value.notes = value
    
    ElMessage.success('退款申请已提交')
    
    // 刷新订单数据
    await OrderDetail()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退款操作失败: ' + (error.message || '未知错误'))
    }
  }
}

// 复制订单号
const copyOrderId = () => {
  navigator.clipboard.writeText(order.value.order_id)
  ElMessage.success('订单号已复制')
}


// 临时备注变量
const tempNote = ref('')

// 添加备注
const addNote = () => {
  tempNote.value = order.value.notes || ''
  noteDialogVisible.value = true
}

// 保存备注
const saveNote = async () => {
  try {
    if (!order.value.objectId) {
      throw new Error('订单ID不能为空')
    }

    console.log('正在保存备注:', {
      objectId: order.value.objectId,
      notes: tempNote.value
    })

    // 调用API更新备注
    const response = await updateorder(
      0, // 默认id
      '', // 默认planId 
      '', // 默认name
      order.value.objectId,
      {
        notes: tempNote.value
      }
    )

    console.log('API响应:', response)

    if (response.status !== 200) {
      throw new Error(`保存备注失败，状态码: ${response.status}`)
    }

    // 更新本地订单备注
    order.value.notes = tempNote.value
    ElMessage.success('备注已保存')
    isEditingNote.value = false
    
    // 刷新订单数据
    await OrderDetail()
  } catch (error) {
    console.error('保存备注失败:', error)
    if (error.response) {
      console.error('API响应数据:', error.response.data)
    }
    ElMessage.error('保存备注失败: ' + (error.message || '未知错误'))
  }
}

// 返回
const goBack = () => {
  if (order.value.objectId) {
    router.push({ path: '/order' }) // 直接返回订单列表页
  } else {
    router.push({ path: '/order' }) // 如果没有订单ID也返回列表页
  }
}
</script>

<style scoped>
.status-detail {
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.status-message {
  padding: 10px;
  border-left: 4px solid;
  margin-bottom: 10px;
}

.status-message.warning {
  border-color: #e6a23c;
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-message.success {
  border-color: #67c23a;
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-message.danger {
  border-color: #f56c6c;
  background-color: #fef0f0;
  color: #f56c6c;
}

.status-message.info {
  border-color: #909399;
  background-color: #f4f4f5;
  color: #909399;
}

.note-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
}

.note-content {
  margin-bottom: 15px;
}

.note-text {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-height: 60px;
}

.note-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.order-detail-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.status-info {
  display: flex;
  align-items: center;
  flex-grow: 1;
  margin-left: 20px;
}

.status-desc {
  margin-left: 10px;
  color: #999;
}

.section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.user-info {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-name {
  font-weight: bold;
  margin-right: 15px;
}

.user-id {
  color: #666;
  margin-bottom: 15px;
}

.detail-row {
  display: flex;
  margin-bottom: 10px;
  line-height: 1.5;
}

.detail-row > span {
  margin-right: 30px;
  min-width: 200px;
}

.order-info {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.price-summary {
  margin-top: 20px;
  text-align: right;
  padding-right: 20px;
}

.summary-row {
  margin-bottom: 10px;
}

.summary-row.total {
  font-weight: bold;
  font-size: 16px;
}

.footer {
  margin-top: 30px;
  text-align: center;
}

.el-table {
  margin-top: 15px;
}
</style>